App.Reserves.Controller.ReserveCreate = Backbone.View.extend({
	//Initialize
	initialize: function(){
		App.Utils.mask();
		var controller = this;
		var model = new App.Reserves.Model.Reserve();
		

		var mainOperation = function(){
			controller.model = model;
			controller.init();
        };
		// Number of total requests to be called before mainOperation        
		var done = 1;
		var stores = new App.Reserves.Collection.StoreCollection();
		App.Reserves.Delegate.ReservesDelegate.storeList(stores,{
    		success:function (data) {
    			App.Utils.unmask();    			
    			controller.stores = data;
				done -= 1;
    		    if(done == 0) 
    		    	mainOperation();
            },
        	error:function(data){
        		App.Utils.unmask();
  		  		App.Utils.setFailureMessage('Error reading stores!');
  		  		Backbone.history.navigate("home",true);
        }});

    },
    //Initialize the controller to show the associated view.
	init: function(){
    	// Compile the template using underscore
        this.view = _.template(App.Utils.getView('invalid/view/reserveCreate'));
        this.model.bind("reset", this.render, this);
        this.render();
    },
    events: {
    	"change"      : "change",
        "click a.save": "save"
    },
    render: function(){
    	//Triggers the model refresh to be passed to the view
    	this.model.change();
    	//Renders the view with the associated elements
        $(this.el).html( this.view({
        	model:this.model,
			stores:this.stores
		}) );
    	//Show the view using JQueryMobile
        App.Utils.changePage(this);
		
		App.Utils.renderDate('date', 2012, 2030, this.model.get('date'));
		//Render the initial selected store 
        if (this.model.get('store') != null){
        	this.model.set('store',this.model.get('store').id);
        	$('#store').val(this.model.get('store'));
        	$('#store').selectmenu('refresh');
        }

    	return this;
    },
    //Fired when there is a change event on the view
    change: function (event) {
    	// Apply the change to the model
        var target = event.target;
        var change = {};
        var name = target.id;
        change[name] = target.value;
        //The model attribute is set
        this.model.set(change);        
        
		App.Utils.renderDate('date', 2012, 2030);
        
        //If the event corresponds to a date type 
        //the target will be replaced for the attribute name
        //so the complete field will be validated
        if (name.indexOf("-year") != -1 ||
        		name.indexOf("-month") != -1 ||
        		name.indexOf("-day") != -1){
        	//name is now the model name
        	name = name.split("-")[0];
        }
        
        // Run validation rule (if any) on changed item
        var check = App.Utils.validateItem(this.model,name);
        if (check.isValid === false) {
        	App.Utils.addValidationError(name, check.message);
        } else {
        	App.Utils.removeValidationError(name);
        }
    },
    //Fired to save a entity recently created
    save: function(){
    	//Run validation on all the model fields if it passes the model will be saved
    	var check = App.Utils.validateAll(this.model);
        if (check.isValid === false) {
        	App.Utils.displayValidationErrors(check.messages);
            return false;
        }
        
        var errorCallback = function(data){
    		App.Utils.unmask();
    		App.Utils.setFailureMessage('Error creating App.Reserves.Model.Reserve!');
		  	Backbone.history.navigate("home",true);
        };
        
        App.Utils.mask();
        var model = this.model;
        
        var saveOperation = function(){        	
        	model.prepareModel();
			App.Reserves.Delegate.ReservesDelegate.reserveCreate(model, {
        		success: function(data) {
        			App.Utils.unmask();
      			  	App.Utils.setSuccessMessage('Successfully created!');
      			  	Backbone.history.navigate("reserves",true);
      		  	},
      		  	error: errorCallback
        	});
        };
        
        var modelSet = function(key, value){
        	var setter = {}; 
            setter[key] = value; 
            model.set(setter);
        };
		
		// Number of total requests to be called before saveOperation
        var done = 1;
        
        var store = new App.Reserves.Model.Store({id:this.model.get('store')});
        App.Reserves.Delegate.ReservesDelegate.storeRead(store,{
    		success:function (data) {
    			modelSet("store",data);
    			done -= 1;
    		    if(done == 0) 
    		    	saveOperation();
            },
            error: errorCallback
        });
    }
});
